package com.wzt.lianfirecontrol.activity;

import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.InputType;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;

import com.wzt.lianfirecontrol.R;
import com.wzt.lianfirecontrol.bean.ConstData;
import com.wzt.lianfirecontrol.bean.recode.user.CodeBackModel;
import com.wzt.lianfirecontrol.bean.recode.user.UserInfoModel;
import com.wzt.lianfirecontrol.http.HttpHelper;
import com.wzt.lianfirecontrol.http.json.ParseJsonData;
import com.wzt.lianfirecontrol.http.Url;
import com.wzt.lianfirecontrol.utils.JSONUtil;
import com.wzt.lianfirecontrol.utils.PreferencesUtils;
import com.wzt.lianfirecontrol.utils.StringUtils;
import com.wzt.lianfirecontrol.utils.ToastUtils;
import com.wzt.lianfirecontrol.utils.Utils;

import org.json.JSONObject;

import java.util.HashMap;

import cn.smssdk.EventHandler;
import cn.smssdk.SMSSDK;
/*
* 忘记密码
* */
public class ForgetPasswordActivity extends BaseActivity {

    private EditText et_phone_number;

    private LinearLayout ll_check_code;
    private EditText et_check_code;
    private TextView bt_check_code;
    private boolean isWaitCheckCode = false;// 是否在等待验证码
    private CountDownTimer countDownTimer;// 验证码倒计时

    private EditText et_password;
    private EditText et_new_password;
    private TextView tv_ps_tips;

    private LinearLayout ll_show_password;//显示密码
    private ImageView iv_show_password;
    private boolean showPassword = true;
    private LinearLayout ll_submit;

    private static final int CHANGE_PASSWORD_WHAT = 0;// 修改密码
    private static final int FORGET_PASSWORD_WHAT = 1;// 忘记密码
    private static final int SEND_CODE_WHAT = 3;// 获取验证码
    private static final int CHECK_CODE_WHAT = 4;// 验证验证码
    private static final int CHECK_CODE_ERROR_WHAT = 5;

    private String pageType = "0";// 0忘记密码 1修改密码 2 修改手机号

    EventHandler eh = new EventHandler(){
        @Override
        public void afterEvent(int event, int result, Object data) {
            // TODO 此处不可直接处理UI线程，处理后续操作需传到主线程中操作
            Message msg = new Message();
            msg.arg1 = event;
            msg.arg2 = result;
            msg.obj = data;
            Log.e("xuhan", JSONUtil.beanToJson(data));

            if (result == SMSSDK.RESULT_COMPLETE) {
                //回调完成
                if (event == SMSSDK.EVENT_SUBMIT_VERIFICATION_CODE) {
                    //提交验证码成功
                    msg.what = CHECK_CODE_WHAT;
                } else if (event == SMSSDK.EVENT_GET_VERIFICATION_CODE) {
                    //获取验证码成功
                    msg.what = SEND_CODE_WHAT;
                } else if (event == SMSSDK.EVENT_GET_SUPPORTED_COUNTRIES) {
                    //返回支持发送验证码的国家列表
                }
            }else {
                msg.what = CHECK_CODE_ERROR_WHAT;
            }
            handler.sendMessage(msg);
            isWaitCheckCode = false;
        }
    };

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Bundle bundle = getIntent().getExtras();
        if (null != bundle){
            pageType = bundle.getString(ConstData.PAGETYPE, "0");
        }
        setContentView(R.layout.a_forget_password);
        setImmerseLayout(findViewById(R.id.include_head_title), findViewById(R.id.rl_head_content), false);
        initView();

        //注册一个事件回调监听，用于处理SMSSDK接口请求的结果
        SMSSDK.registerEventHandler(eh);
    }

    private void initView() {
        initHeadView();
        initContentView();
    }

    private void initHeadView() {
        View include_head_title = findViewById(R.id.include_head_title);
        include_head_title.setBackground(getResources().getDrawable(R.drawable.shape_head_title_bg_frame));

        ImageView iv_back = findViewById(R.id.iv_back);
        iv_back.setImageResource(R.drawable.back_white);
        iv_back.setVisibility(View.VISIBLE);

        TextView tv_title = findViewById(R.id.tv_title);
        tv_title.setTextColor(getResources().getColor(R.color.white));
        switch (pageType){
            case "1":
                tv_title.setText("修改密码");
                break;
            case "2":
                tv_title.setText("更换手机号");
                break;
            default:
                tv_title.setText("重置密码");
                break;
        }
    }

    private void initContentView() {
        et_phone_number = findViewById(R.id.et_phone_number);
        ll_check_code = findViewById(R.id.ll_check_code);
        et_check_code = findViewById(R.id.et_check_code);
        bt_check_code = findViewById(R.id.bt_check_code);
        bt_check_code.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (StringUtils.isEmpty(et_phone_number.getText().toString())){
                    ToastUtils.showToast(ForgetPasswordActivity.this, "手机号不能为空");
                    return;
                }
                if (!isWaitCheckCode) {
                    // 请求验证码，其中country表示国家代码，如“86”；phone表示手机号码，如“13800138000”
                    SMSSDK.getVerificationCode("86", et_phone_number.getText().toString());
                }
            }
        });

        et_password = findViewById(R.id.et_password);
        et_new_password = findViewById(R.id.et_new_password);
        tv_ps_tips = findViewById(R.id.tv_ps_tips);

        ll_show_password = findViewById(R.id.ll_show_password);
        iv_show_password = findViewById(R.id.iv_show_password);
        ll_show_password.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (showPassword){
                    iv_show_password.setImageResource(R.mipmap.icon_password_uncheck);
                    et_password.setInputType(InputType.TYPE_CLASS_TEXT
                            | InputType.TYPE_TEXT_VARIATION_PASSWORD);
                    et_new_password.setInputType(InputType.TYPE_CLASS_TEXT
                            | InputType.TYPE_TEXT_VARIATION_PASSWORD);
                }else {
                    iv_show_password.setImageResource(R.mipmap.icon_password_check);
                    et_password.setInputType(InputType.TYPE_CLASS_TEXT
                            |InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
                    et_new_password.setInputType(InputType.TYPE_CLASS_TEXT
                            |InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
                }
                showPassword = !showPassword;
                if (!StringUtils.isEmpty(et_password.getText().toString())) {
                    et_password.setSelection(et_password.getText().toString().length());
                }
                if (!StringUtils.isEmpty(et_new_password.getText().toString())) {
                    et_new_password.setSelection(et_new_password.getText().toString().length());
                }
            }
        });
        iv_show_password.setImageResource(R.mipmap.icon_password_check);
        et_password.setInputType(InputType.TYPE_CLASS_TEXT
                |InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
        et_new_password.setInputType(InputType.TYPE_CLASS_TEXT
                |InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
        et_password.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.length() > 0) {
                    for (int i = 0; i < s.length(); i++) {
                        char c = s.charAt(i);
                        if (c >= 0x4e00 && c <= 0X9fff) { // 根据字节码判断
                            // 如果是中文，则清除输入的字符，否则保留
                            s.delete(i,i+1);
                        }
                    }
                }
            }
        });
        et_new_password.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.length() > 0) {
                    for (int i = 0; i < s.length(); i++) {
                        char c = s.charAt(i);
                        if (c >= 0x4e00 && c <= 0X9fff) { // 根据字节码判断
                            // 如果是中文，则清除输入的字符，否则保留
                            s.delete(i,i+1);
                        }
                    }
                }
            }
        });

        ll_submit = findViewById(R.id.ll_submit);
        if ("2".equals(pageType)){
            ((TextView)ll_submit.findViewById(R.id.tv_bing_now)).setText("下一步");
        }
        ll_submit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if ("0".equals(pageType) || "2".equals(pageType)){
                    if (StringUtils.isEmpty(et_check_code.getText().toString())){
                        ToastUtils.showToast(ForgetPasswordActivity.this, "验证码不能为空");
                        return;
                    }
                    SMSSDK.submitVerificationCode("86", et_phone_number.getText().toString(), et_check_code.getText().toString());
                    return;
                }
                //发送请求
                initChangePwHttpHelper();
            }
        });

        switch (pageType){
            case "1":// 1修改密码
                et_phone_number.setVisibility(View.GONE);
                ll_check_code.setVisibility(View.GONE);
                et_password.setVisibility(View.VISIBLE);
                et_password.setHint("请输入旧密码");
                et_new_password.setVisibility(View.VISIBLE);
                tv_ps_tips.setVisibility(View.VISIBLE);
                ll_show_password.setVisibility(View.VISIBLE);
                break;
            case "2":// 2 修改手机号
                et_phone_number.setVisibility(View.VISIBLE);
                ll_check_code.setVisibility(View.VISIBLE);
                et_password.setVisibility(View.GONE);
                et_new_password.setVisibility(View.GONE);
                tv_ps_tips.setVisibility(View.GONE);
                ll_show_password.setVisibility(View.INVISIBLE);
                break;
            default:// 0忘记密码
                et_phone_number.setVisibility(View.VISIBLE);
                ll_check_code.setVisibility(View.VISIBLE);
                et_password.setVisibility(View.VISIBLE);
                et_new_password.setVisibility(View.GONE);
                tv_ps_tips.setVisibility(View.VISIBLE);
                ll_show_password.setVisibility(View.VISIBLE);
                break;
        }
    }

    /**
     * 修改密码
     */
    private void initChangePwHttpHelper() {
        //判断数据是否正确
        switch (pageType){
            case "1":
                if (StringUtils.isEmpty(et_password.getText().toString())){
                    ToastUtils.showToast(ForgetPasswordActivity.this, "旧密码不能为空");
                    return;
                }
                if (StringUtils.isEmpty(et_new_password.getText().toString())){
                    ToastUtils.showToast(ForgetPasswordActivity.this, "新密码不能为空");
                    return;
                }
                if (!Utils.chechPsIsTrue(et_password.getText().toString())){
                    ToastUtils.showToast(ForgetPasswordActivity.this, "密码为6-16位数字和字母组合");
                    return;
                }
                break;
            default:
                if (StringUtils.isEmpty(et_phone_number.getText().toString())){
                    ToastUtils.showToast(ForgetPasswordActivity.this, "手机号不能为空");
                    return;
                }
                if (StringUtils.isEmpty(et_password.getText().toString())){
                    ToastUtils.showToast(ForgetPasswordActivity.this, "密码不能为空");
                    return;
                }
                if (!Utils.chechPsIsTrue(et_password.getText().toString())){
                    ToastUtils.showToast(ForgetPasswordActivity.this, "密码为6-16位数字和字母组合");
                    return;
                }
                break;
        }
        isRefreshing = true;

        HashMap<String, Object> url_params = new HashMap<>();
        switch (pageType){// 1修改密码 2 修改手机号 0忘记密码
            case "1":
                url_params.put("oldPassword", et_password.getText().toString());
                url_params.put("password", et_new_password.getText().toString());
                url_params.put("id", UserInfoModel.getUserInfo(this).getId());
                break;
            default:
                url_params.put("phone", et_phone_number.getText().toString());
                url_params.put("password", et_password.getText().toString());
                url_params.put("zone", "86");
                break;
        }
        String url;
        int what;
        switch (pageType){
            case "1":
                url = Url.CHANGE_PASSWORD_URL;
                what = CHANGE_PASSWORD_WHAT;
                break;
            default:
                what = FORGET_PASSWORD_WHAT;
                url = Url.FORGET_PASSWORD_URL;
                break;
        }
        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put(ConstData.JSONOBJECT, JSONUtil.mapToJSonStr(url_params));

        LoginHttpHelper loginHttpHelper = new LoginHttpHelper(this, url, what, handler, true, hashMap);
        loginHttpHelper.setParseJsonData(new LoginParseJsonData());
        loginHttpHelper.getHttpRequest(true);
    }

    class LoginHttpHelper extends HttpHelper {

        public LoginHttpHelper(BaseActivity activity, String url, int what, Handler handler, boolean isPost, HashMap<String, String> params) {
            super(activity, url, what, handler, isPost, params);
        }
    }

    protected class LoginParseJsonData extends ParseJsonData {

        public LoginParseJsonData() {
        }

        @Override
        public void analyzeResult(String dataStr, Bundle bundle, int what) {
            switch (what){
                case CHANGE_PASSWORD_WHAT:
                    if ("{}".equals(dataStr)){
                        bundle.putBoolean(REQUEST_OK, true);
                    }
                    break;
            }
        }
    }

    @Override
    protected void dealWithMyMsgs(Message msg) {
        super.dealWithMyMsgs(msg);
        Bundle bundle = msg.getData();
        isRefreshing = false;
        try {
            if (msg.what == SEND_CODE_WHAT){
                isWaitCheckCode = true;
                getCheckCodeAction();
                return;
            }else if (msg.what == CHECK_CODE_WHAT){
                if (pageType.equals("2")){
                    // 更换手机号
                    if (StringUtils.isEmpty(et_phone_number.getText().toString())){
                        ToastUtils.showToast(ForgetPasswordActivity.this, "手机号不能为空");
                        return;
                    }
                    PreferencesUtils.putString(this, ConstData.CHANGEDPHONE, et_phone_number.getText().toString());
                    finish();
                }else {
                    initChangePwHttpHelper();
                }
                return;
            }else if (msg.what == CHECK_CODE_ERROR_WHAT){
                HashMap<String, String> hashMap = JSONUtil.jsonObjectToMap(JSONUtil.beanToJson(msg.obj));
                if (hashMap.containsKey("detailMessage")) {
                    CodeBackModel codeBackModel = JSONUtil.jsonObjectToBean(new JSONObject(hashMap.get("detailMessage")), CodeBackModel.class);
                    ToastUtils.showToast(this, codeBackModel.getDetail());
                }
                return;
            }
        }catch (Exception e){}

        if (!bundle.getBoolean(ParseJsonData.REQUEST_OK) ||
                !ParseJsonData.REQUEST_OK_CODE.equals(bundle.getString(ParseJsonData.ERROR_CODE))){
            if (ParseJsonData.REQUEST_OK_CODE.equals(bundle.getString(ParseJsonData.ERROR_CODE))){
                finish();
                return;
            }

            return;
        }
        switch (msg.what){
            case CHANGE_PASSWORD_WHAT:
                ToastUtils.showToast(this, "修改成功");
                tv_ps_tips.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        finish();
                    }
                }, 1000);
                break;
        }
    }

    /**
     * 获取验证码动作
     */
    private void getCheckCodeAction() {
        if (null == countDownTimer) {
            countDownTimer = new CountDownTimer(60000, 1000) {
                @Override
                public void onTick(long l) {
                    bt_check_code.setText((int) (l / 1000) + "");
                }

                @Override
                public void onFinish() {
                    bt_check_code.setText("重新获取");
                    bt_check_code.setTextColor(ForgetPasswordActivity.this.getResources().getColor(R.color.main_color));
                    bt_check_code.setBackground(ForgetPasswordActivity.this.getResources().getDrawable(R.drawable.shape_check_code_bt_bg));
                    isWaitCheckCode = false;
                }
            };
        } else {
            countDownTimer.cancel();
        }
        countDownTimer.start();
        bt_check_code.setTextColor(ForgetPasswordActivity.this.getResources().getColor(R.color.gray));
        bt_check_code.setBackground(ForgetPasswordActivity.this.getResources().getDrawable(R.drawable.shape_uncheck_code_bt_bg));
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (null != countDownTimer){
            countDownTimer.cancel();
        }
        SMSSDK.unregisterEventHandler(eh);
    }



}
